<?php

namespace App\Http\Controllers\BaseData;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\Menu;
use Illuminate\Support\Facades\DB;

class MenuController extends Controller
{
    /**
     * label a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        // $a=new Menu;
        //  dd( $a instanceof Menu );
        if (post("?")) {
            return (Menu::orderBy("sort")->treeGrid());
        } else {
            return view('BaseData.MenuController.index', F());
        }
    }

    public function add()
    {
        // dd(Menu::treeGrid()->toArray());
        if (post("?")) {
            $data = post('data');
            try {
                begin();
                Menu::create(array_filter($data));
                commit();
            } catch (\Exception $e) {
                rollback();
                return error($e->getMessage());
            }
            return success("保存成功！");
        } else {
            // $param = F();
            $param['selectdata']['data'] = Menu::treeGrid(true);
            $param['selectdata']['name'] = "data[parent_id]";
            return view('BaseData.MenuController.add',  $param);
        }
    }

    public function edit()
    {
        $id = get('id');
        $gdata = Menu::where(['id' => $id])->first();
        if (post("?")) {
            $data = post('data');
            try {
                begin();
                $gdata->update(unsetNull($data));
                commit();
            } catch (\Exception $e) {
                rollback();
                return error($e->getMessage());
            }

            return success("保存成功！");
        } else {
            // $param = F();
            $param['selectdata']['data'] = Menu::treeGrid(true);
            $param['selectdata']['name'] = "data[parent_id]";
            $param['selectdata']['default'] = $gdata->parent_id;

            $param['gdata'] = $gdata;
            return view('BaseData.MenuController.add',  $param);
        }
    }

    public function delete()
    {
        $ids = get('ids');
        try {
            begin();
            Menu::whereIn("id", $ids)->delete();
            commit();
        } catch (\Exception $e) {
            rollback();
            return error($e->getMessage());
        }
        return success("删除成功！");
    }
}
